package com.topway.dsmflex.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.topway.dsmflex.model.base.DataMonitorBean;
import com.topway.dsmflex.model.base.DataPropertyBean;
import com.topway.dsmflex.model.base.DataRunBean;
import com.topway.dsmflex.model.base.Element;
import com.topway.dsmflex.util.ObjectSerializable;


/**
 * 
 * @author liusy 2013-05-2
 *
 */
public abstract class BaseServices<T> {
	
	protected Map<String,T> mapTable = null;

	
	private String dataFilePath  = "";

	
	@SuppressWarnings("unchecked")
	public BaseServices(String dataFilePath)
	{
		this.dataFilePath = dataFilePath;
		mapTable = (Map<String, T>) ObjectSerializable.readObject(dataFilePath);
		if(null==mapTable)
			mapTable = new HashMap<String,T>();
	}
	
	private int saveTableConfig(T dt)
	  {
		((DataRunBean) dt).Run();
		((Element) dt).removePropertyChangeListener();
		((DataMonitorBean) dt).setSize(0);
		((DataMonitorBean) dt).setState(0);
		((DataPropertyBean) dt).setCheck(1);
		mapTable.put(((DataPropertyBean) dt).getName(), dt);
		return 1;
	  }
	  
	  public int saveTableConfigList(List<T> dtList)
	  {
		int i = 0;
		this.mapTable = new HashMap<String,T>();
		for (i = 0; i < dtList.size(); i++) {
			saveTableConfig(dtList.get(i));
		}
		ObjectSerializable.writeObject(dataFilePath, mapTable);
		return i;
	  }
	  
	  public int saveTableConfigList(T [] dtList)
	  {
		  T dt;
		  this.mapTable = new HashMap<String,T>();
		for (int i = 0; i < dtList.length; i++) {
			dt = (T)dtList[i];
			saveTableConfig(dt);
		}
		ObjectSerializable.writeObject(dataFilePath, mapTable);
		return 1;
	  }
	  
	  
		public List<T> getAllDataTable() {
			List<T> list= new ArrayList<T>();
	    	for (Entry<String, T> entry : mapTable.entrySet()) {
	    		list.add(entry.getValue());
	    	}	
	    	return list;
		}
}
